package com.qdxwx.web.controller.ajax;

import com.qdxwx.common.constants.CacheConstants;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.utils.ObjectUtils;
import com.qdxwx.data.service.coupon.CouponCodeService;
import com.qdxwx.data.service.course.CourseService;
import com.qdxwx.data.service.order.OrderService;
import com.qdxwx.models.coupon.CouponCodeDTO;
import com.qdxwx.models.course.Course;
import com.qdxwx.models.order.Order;
import com.qdxwx.web.controller.BaseController;
import com.qdxwx.web.utils.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Coupon 优惠券 接口
 * @author developer
 */
@Controller
@RequestMapping("/ajax/coupon")
public class AjaxCouponController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(AjaxCouponController.class);

    @Autowired
    private CouponCodeService couponCodeService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private CourseService courseService;

    /**
     * 验证优惠券的限制范围
     */
    @RequestMapping("/check.json")
    @ResponseBody
    public AjaxResult checkCouponByCode(HttpServletRequest request) {
        long userId = LoginUser.getUserId(request);// 用户id
        if (userId == 0) {
            return AjaxResult.error("此功能需要登录后操作，请先登录！");
        }
        if ("OFF".equals(CacheConstants.COUPON_IS_OPEN)) {
            return AjaxResult.error("【优惠券】功能未启用！");
        }
        String couponCode = request.getParameter("couponCode");// 优惠券编码
        String orderNo = request.getParameter("orderNo");// 订单编号

        // 查询优惠券编码
        CouponCodeDTO couponCodeDTO = couponCodeService.getDTOByCode(couponCode);
        if (ObjectUtils.isNull(couponCodeDTO)) {
            return AjaxResult.error("优惠券编码不存在");
        }

        List<Course> courses;
        if (orderNo != null && !orderNo.equals("")) {// 订单课程集合
            courses = courseService.getListByOrderNo(orderNo);// 订单课程集合
        } else {// 查询购物车的课程集合
            courses = courseService.getListByShopCart(userId, 1);
        }

        if (courses == null || courses.size() == 0) {// 如果购物车为空
            return AjaxResult.error("购物车不能为空");
        }
        //判断优惠券是否冻结（已下单）
        Order order = orderService.getByOrderNo(orderNo);
        //重新支付验证
        if (ObjectUtils.isNotNull(order) && couponCodeDTO.getStatus() == 6 && !Objects.equals(order.getCouponCodeId(), couponCodeDTO.getId())) {
            return AjaxResult.error("此优惠券已在其他订单中使用！");
        } else if (ObjectUtils.isNull(order) && couponCodeDTO.getStatus() == 6) {//未下订单
            return AjaxResult.error("此优惠券已在其他订单中使用！");
        }
        // 验证优惠券编码
        Map<String, Object> map = couponCodeService.checkCode(couponCodeDTO, courses, userId);
        if (map.get("msg") == "true") {
            map.put("couponCodeDTO", couponCodeDTO);
            return AjaxResult.success(map);
        } else {
            return AjaxResult.error(map.get("msg").toString());
        }
    }
}